package com.qiantu.api.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.google.gson.Gson;
import com.qiantu.api.entity.LoginBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    private static final String AES_KEY = "3lxwJp0HsrMM3cE1rtFFpeKcDnI6ySaT";
    private static final String LOG = "FileUtils";

    /**
     * @param path the name of the file on the sd-card (+ path if needed)
     * @return
     */
    public static List<LoginBean> loadAccountsFromFile(Context context) {

//        File sdcard = Environment.getExternalStorageDirectory();
        File sdcard = context.getFilesDir();

        // Get the text file
        File file = new File(sdcard, "accountList.txt");
        //读取文件内容保存到resultStr
        String resultStr = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] b = new byte[fileInputStream.available()];
            fileInputStream.read(b);
            resultStr = new String(b);
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("读文件出错");
        }
        //将读取的String结果转化成List<>
        List<LoginBean> tempList = new ArrayList<LoginBean>();
        if(resultStr == null){
            return null;
        }

        resultStr = Md5Util.decrypt(resultStr,AES_KEY,AES_KEY.substring(0,16));
        try {
            JSONArray jsonArray = new JSONArray(resultStr);
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
                    LoginBean loginBean = new Gson().fromJson(jsonArray.get(i).toString(), LoginBean.class);
                    /*if(loginBean.getUserInfo().getPhone().equals("13812345678"))
                        continue;*/
                    tempList.add(loginBean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("转化list出错");
        }

        return tempList;
    }

    public static boolean saveAccounts(Context context,List<LoginBean> list) {
        return saveToSdCard(context, list, "accountList.txt");
    }

    /**
     * @param list
     * @param path
     */
    public static boolean saveToSdCard(Context context,List<LoginBean> list, String path) {
        boolean isAvailable = false;    //SD是否可读
        if(list == null){
            return false;
        }
//        File sdcard = Environment.getExternalStorageDirectory();
        File sdcard = context.getFilesDir();
        FileOutputStream fileOutputStream = null;
        File saved = new File(sdcard, path);
        if (!saved.exists()) {
            try {
                saved.createNewFile();
            } catch (IOException e) {
                Log.e(LOG, e.toString());
            }
        }
        // 可存储的字符串数据
        String listStr = new Gson().toJson(list);
        listStr = Md5Util.encrypt(listStr,AES_KEY,AES_KEY.substring(0,16));
        //判断SD卡是否可读写
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            isAvailable = true;
            try {
                fileOutputStream = new FileOutputStream(saved);
                fileOutputStream.write(listStr.getBytes());
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return isAvailable;
    }



}
